/**
 * parser.cpp
 * Command parser.
 * By Group 1
 */
#include "parser.h"
#include <cstdlib>
#include <iostream>
#include "tftpclient.h"

void readCommands(void)
{
    string function;
    bool continueLoop = true;

    while(cin.eof() != true && continueLoop)
    {
        cout << "tftp> ";
        cin >> function;
        continueLoop = processLine(function);
    }
}

bool processLine(string &function)
{
    if (function == "put")
    {
        string parameter;
        char next = cin.get();
        if(next == (*"\n") )
        {
            cout << "Usage: put [filename]" << endl;
        }
        else
        {
            getline(cin,parameter);
            TFTPsendFile(parameter);
        }
    }
    else if (function == "get")
    {
        string parameter;
        char next = cin.get();
        if(next == (*"\n") )
        {
            cout << "Usage: get [filename]" << endl;
        }
        {
            getline(cin,parameter);
            TFTPgetFile(parameter);
        }
    }
    else if (function == "echo")
    {
        string parameter;
        char next = cin.get();
        if(next == (*"\n") )
        {
            cout << "Usage: echo [filename]" << endl;
        }
        {
            getline(cin,parameter);
            TFTPecho(parameter);
        }
    }
    else if (function == "host")
    {
        string parameter;
        char next = cin.get();
        if(next == (*"\n") )
        {
            cout << "Please indicate the new host you wish to connect to: ";
        }
        getline(cin,parameter);
        loadHostAddress(parameter.c_str());
    }
    else if (function == "who")
        printHostAddress();
    else if (function == "dieserverdie")
        TFTPdie();
    else if (function == "help")
        printHelp();
    else if (function == "exit" || function == "quit")
        return false;
    else
    {
        cout << "The entered command is invalid. For help, type: help" << endl;
    }
    return true;
}

void printHelp(void)
{
    cout << endl << "\t\tTFTP Client Help" << endl;
    cout << "This program supports the following commands:" << endl;
    cout << "put [filename]: Uploads a file to the server." << endl;
    cout << "get [filename]: Downloads a file to the server." << endl;
    cout << "echo [message]: NON-STANDARD - Sends a message to the server and expects the same one back as an answer." << endl;
    cout << "host [hostaddress]: Changes the host address to which the client connects.." << endl;
    cout << "who: Prints the host address." << endl;
    cout << "dieserverdie: NON-STANDARD - Forces the server to exit the main loop and shutdown. It has to be manually restarted later on." << endl; //Agregamos esto como una manera alegre de apagar el servidor, para no tener que hacerle un kill.
    cout << "help: Prints this help message." << endl;
    cout << "exit | quit: Exits the program." << endl;
    cout << endl;
    cout << "Brought to you by Group 1" << endl << endl;
}
